<template>
    <div class="downFile toolbar-link">
        <el-popover :width="600" trigger="click" ref="popverRef" :visible="visible">
            <template #reference>
                <div class="clickDiv" @click="tooglePopver">
                    <!-- 生成中  progress_total>0 。。。。 -->
                    <div class="box" v-if="objParams.progress_total>0&&taskList.length">
                        <div class="under"></div>
                        <span>
                            <el-icon size="17">
                                <Download />
                            </el-icon>
                        </span>
                    </div>
                    <div v-else>
                        <!-- 生成成功！----- -->

                        <el-badge :max="9" :value="objParams.complete_total" :show-zero="false" class="item">
                            <div class="finished-down">
                                <el-icon size="20">
                                    <Download />
                                </el-icon>
                            </div>
                        </el-badge>
                    </div>
                </div>
            </template>
            <div class="content-body">
                <div class="message-empty" v-if="!taskList.length">
                    <img src="@/assets/images/notData.png" alt="notData" />
                    <div style="padding-top:10px;">{{$t("merak.no_exported_file_is_available")}}</div>
                </div>


                <div v-else>
                    <div class="down-header">
                        <span>{{$t("merak.export_file")}}</span>
                        <span class="clear-item" @click="clearAllFun">{{$t("merak.clear_list")}}</span>
                    </div>
                    <div class="down-item-content">

                        <el-scrollbar max-height="400px">
                            <div class="down-item" v-for="(tItem,index ) in taskList" :key="index">
                                <div class="time-label">{{tItem.time}}</div>

                                <div class="file-item" v-for="(cItem,cIndex) in tItem.list" :key="cIndex">
                                    <div class="left-name">
                                        <span class="file-icon">
                                            <el-icon size="14px" v-if="cItem.file_type=='image'">
                                                <Picture />
                                            </el-icon>
                                            <el-icon size="14px" v-else>
                                                <Document />
                                            </el-icon></span>

                                        <span
                                            :class="{'file-name':['progress','complete'].includes(cItem.status),'file-name-err':(['error','delete'].includes(cItem.status)||cItem.expire_status)}">{{cItem.file_name}}</span>

                                        <div
                                            :class="{'tip-waring':cItem.status=='complete','tip-err':(['error','delete'].includes(cItem.status)||cItem.expire_status)}">
                                            {{cItem.info}}</div>

                                    </div>
                                    <div class="file_size">{{cItem.file_size}}</div>
                                    <div class="label-status"
                                        :class="{'success':cItem.status=='complete','ing':cItem.status=='progress','fail':(['error','delete'].includes(cItem.status)||cItem.expire_status)}">
                                        {{cItem.status_label}} <span v-if="cItem.status=='progress'">
                                            {{cItem.remainder}}</span>
                                    </div>
                                    <div class="opration">
                                        <span v-if="cItem.file_type=='image'">
                                            <a class="icon-class down" @click="downImage(cItem.file_path)"
                                                v-if="cItem.status=='complete'&&!cItem.expire_status"> <el-icon>
                                                    <Download />
                                                </el-icon></a>
                                        </span>
                                        <span v-else>
                                            <a class="icon-class down" :href="cItem.file_path"
                                                v-if="cItem.status=='complete'&&!cItem.expire_status"> <el-icon>
                                                    <Download />
                                                </el-icon></a>
                                        </span>



                                        <span class="icon-class close" @click="closeItem(cItem,cIndex,index)"><el-icon>
                                                <Close />
                                            </el-icon></span>
                                    </div>

                                </div>
                            </div>
                        </el-scrollbar>
                    </div>
                </div>

            </div>
        </el-popover>
    </div>

</template>
<script setup lang="ts">
    import { ref, reactive, onMounted, nextTick, watch,getCurrentInstance  } from "vue";
    import { ElNotification } from 'element-plus';
    import { getTaskListApi, delTaskOneApi, delTaskAllApi } from '@/api/modules/public.ts';
    import { useDefaultStore } from "@/stores/modules/default";
    import { storeToRefs } from "pinia";
    import { confirmWarningMsg, } from "@/utils/messageUtils";
    const { proxy } = getCurrentInstance();
    // proxy.$t("merak.is_del_expor")
    const defaultStore = useDefaultStore();
    const popverRef = ref(null);
    const visible = ref < Boolean > (false);//prop显示
    const loadingDown = ref < Boolean > (true);//下载进行中
    const emptyShow = ref < Boolean > (false);
    const initParams = {
        currentPage: 1,
        pageSize: 30
    }
    const listParams = ref({
        currentPage: 1,
        pageSize: 30
    });
    //关闭
    const closePopover = (event) => {
        console.log(popverRef.value.$el)
        console.log(event.target)
        const isOutside = !popverRef.value.$el.contains(event.target);
        //点击按钮
        const innerHtml = document.getElementsByClassName("clickDiv")[0].contains(event.target);
        //点击内容
        const innerHtmlBool = document.getElementsByClassName("content-body")[0].contains(event.target);

        if (isOutside && !innerHtml && !innerHtmlBool) {
            visible.value = false;
            defaultStore.downVisable = false;
        }

    }
    watch(() => defaultStore.downVisable, (newVal, oldVal) => {
        // console.log(newVal,"触发。。。。")

        visible.value = newVal;
        if (newVal) {
            listParams.value = { ...initParams };
            initTaskList();
            // 添加全局点击事件监听
            document.addEventListener('click', closePopover);
        } else {
            document.removeEventListener('click', closePopover);
        }
    })

    const tooglePopver = () => {

        let visBool = !visible.value;
        console.log(visBool)
        visible.value = visBool;
        defaultStore.downVisable = visBool;

    }


    onMounted(() => {
        defaultStore.downVisable = false;//初始化设置缓存值为false
        listParams.value = { ...initParams };
        initTaskList();
        //1分钟后定时请求
        setInterval(() => {
            initTaskList();
        }, 1000 * 60 * 1)
        // setTimeout(() => {
        //     loadingDown.value = false;
        //     ElNotification({
        //         message: '所有文件均已生成!!!',
        //         type: 'success',
        //     })
        // }, 3000)
    })
    //初始化任务列表

    const objParams = ref({});
    const taskList = reactive([]);
    const initTaskList = () => {
       
        getTaskListApi(listParams.value).then(res => {

            if (res.code == ResultEnum.SUCCESS) {
                let data = res.data;
                objParams.value = data.table_data;
                if (!data.table_data?.list) {
                    emptyShow.value = true;
                }
                else {
                    emptyShow.value = false;
                    Object.assign(taskList, data.table_data.list);
                }

            }
        })
    }

    //图片下载
    const downImage = (imageUrl) => {
        console.log(imageUrl)
        getBase64Image(imageUrl).then(base64 => {
            console.log(base64)
            var oA = document.createElement('a')
            oA.download = new Date().getTime(); // 设置下载的文件名，默认是'下载'
            oA.href = base64
            document.body.appendChild(oA);
            oA.click()

            oA.remove() // 下载之后把创建的元素删除
        })
    }

    const getBase64Image = src => {
        return new Promise(resolve => {
            const img = new Image()
            img.crossOrigin = ''
            img.src = src
            img.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = img.width
                canvas.height = img.height
                const ctx = canvas.getContext('2d') 

                ctx?.drawImage(img, 0, 0, img.width, img.height);
               
                const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
                const dataURL = canvas.toDataURL('image/' + ext)
                resolve(dataURL)
            }
        })
    }
    //删除单条任务
    const closeItem = (cItem, index, pIndex) => {
        confirmWarningMsg({
            msg: proxy.$t("merak.is_del_expor"),
            callback: val => {
                if (val == "confirm") {
                    ///成功
                    delOne(cItem.id).then(suc => {
                        // 如果list有多条只删除一条
                        if (taskList[pIndex].list.length > 1) {
                            taskList[pIndex].list.splice(index, 1);
                            return;
                        }
                        //如果list只有一条删除当前所有对象
                        taskList.splice(pIndex, 1);

                    })

                }
            }
        });
    }

    const delOne = (id) => {
        return delTaskOneApi({ id: id }).then(res => {
            if (res.code == ResultEnum.SUCCESS) {
                return Promise.resolve()
            } else {
                return Promise.reject()
            }
        })
    }




    //删除所有列表
    const clearAllFun = () => {
        confirmWarningMsg({
            msg: proxy.$t("是否确认清空所有导出文件?"),
            callback: val => {
                if (val == "confirm") {
                    ///成功
                    delAll().then(suc => {
                        taskList.splice(0, taskList.length);

                    })


                }
            }
        });
    }


    const delAll = () => {
        return delTaskAllApi().then(res => {
            if (res.code == ResultEnum.SUCCESS) {
                return Promise.resolve()
            } else {
                return Promise.reject()
            }
        })
    }

</script>
<style lang="scss" scoped>
    @import url(./index.scss);
</style>